package com.android.justcook;

import android.util.Log;

public class RecipeGiver {
	private String recipeText = null;
	private int currentPosition = 0;
	private int currentStep = 0;
	private static final int GO_RIGHT = 1;
	private static final int GO_LEFT = -1; 
	
	public String nextStep(){
		String subSentence = null;
		
		int secondIndex = findADot(this.recipeText, currentPosition, GO_RIGHT);
		
		if(currentPosition < this.recipeText.length() - 1 && currentPosition != 0) {
			subSentence = recipeText.substring(currentPosition + 1, secondIndex);
		} else {
			subSentence = recipeText.substring(currentPosition, secondIndex);
		}
		currentPosition = secondIndex;
		
		if(subSentence.length() != 0) {
			currentStep++;
		}
		
		return subSentence;
	}
	
	public String backStep() {
		String subSentence = null;
		
		if(currentPosition < 0) {
			currentPosition = 0;
		}
		
		int firstIndex = findADot(this.recipeText, currentPosition, GO_LEFT);
		currentPosition = firstIndex;
		firstIndex = findADot(this.recipeText, currentPosition, GO_LEFT);
		
		Log.d("debug", "" + firstIndex+1 + " " + currentPosition);
		
		if(firstIndex != 0){
			subSentence = recipeText.substring(firstIndex + 1, currentPosition);
		} else {
			subSentence = recipeText.substring(firstIndex, currentPosition);
		}
		

		if(subSentence.length() != 0) {
			currentStep--;
		}
		
		return subSentence;
	}
	
	public int getCurrentStep() {
		return currentStep;
	}

	public void setCurrentStep(int currentStep) {
		this.currentStep = currentStep;
	}

	public int findADot(String givenString, int currentPosition, int direction) {
		int nextDotIndex = currentPosition;
		int stringMaxLength = givenString.length();
		
		for(int i = currentPosition + direction; i < stringMaxLength && i >= 0; i += direction) {

			nextDotIndex = i;
			if(givenString.charAt(i) == '.') {
				break;
			}
		}
		
		return nextDotIndex;
	}
	
	public RecipeGiver(String recipeText) {
		super();
		this.recipeText = recipeText;
	}

	public String getRecipeText() {
		return recipeText;
	}

	public void setRecipeText(String recipeText) {
		this.recipeText = recipeText;
		this.currentPosition = 0;
	}

	public int getCurrentPosition() {
		return currentPosition;
	}

	public void setCurrentPosition(int currentPosition) {
		this.currentPosition = currentPosition;
	}
}
